package com.sjz.file;

import com.sjz.service.FileService;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FileActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  //得到layout文件对应的main.xml的页面样式
        Button button = (Button) this.findViewById(R.id.button);  //得到保存按钮的元素
        button.setOnClickListener(new ButtonClickListener());//触发点击事件
    }
    
    private final class ButtonClickListener implements View.OnClickListener{

		public void onClick(View v) {
			EditText filenameText = (EditText) findViewById(R.id.filename);//得到文件名称输入框元素对象
			EditText contentText = (EditText) findViewById(R.id.filecontent);//得到文件内容输入框元素对象
			String filename = filenameText.getText().toString();//得到文件名称输入框的值
			String content = contentText.getText().toString();//得到文件内容输入框的值
			FileService service = new FileService(getApplicationContext());
			//test1(service,filename,content);
			 // test2(service,filename,content);
			test3(service,filename,content);
		}
		
		
		/****
		 * 保存数据到sdcard
		 * @param service
		 * @param filename
		 * @param content
		 */
		public void test3(FileService service, String filename, String content) {
			try {
				//判断SDCard是否存在，并且可以读写   判断状态
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					service.saveToSDCard(filename, content);
					Toast.makeText(getApplicationContext(), R.string.success, 1).show();
				}else{
					Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();
				}				
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
				e.printStackTrace();
			}
			
		}


		/****
		 * 追加模式
		 * @param service
		 * @param filename
		 * @param content
		 */
		public void test2(FileService service,String filename,String content) {
			try {
				service.saveAppend(filename, content);
				Toast.makeText(getApplicationContext(), R.string.success, 1).show();
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
				e.printStackTrace();
			}
		}


		/****
		 * 保存文件    使用私有模式
		 * @param service
		 * @param filename
		 * @param content
		 */
		public void test1(FileService service,String filename,String content){
			try {
				service.save(filename, content);
				Toast.makeText(getApplicationContext(), R.string.success, 1).show();
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
				e.printStackTrace();
			}
		}
    	
    }
}